from __future__ import with_statement
import simplejson
import sys
import csv

def main():
    with open(sys.argv[1], 'r') as f_in:
        courses = simplejson.load(f_in)

#<Dept. Code, 2-4 char>,<Course no., 3 chars, 1 letter?>,<Course Name 80 chars>,<Weekday 2 chars>,<startTime 24hr>,<endTime 24hr>

    output = []

    for c in courses.values():
        course_data = [None,
                       None,
                       None,
                       None,
                       None,
                       None,
                       None,
                       None,
                       None,
                       None,
                      ]
        if c is None:
            continue

        for o in c:
            if o['Time Days/Date'] is None:
                continue

            if o['Comp Sec'] is not '':
                klass, section = o['Comp Sec'].split(' ')
                course_data[0] = o['Subject']
                course_data[1] = o['Catalog']
                course_data[2] = o['Units']
                course_data[3] = o['Title']
                course_data[4] = klass
                course_data[5] = section
                course_data[9] = sys.argv[2]

            course_data[7] = o['Time Days/Date'][1]
            course_data[8] = o['Time Days/Date'][2]

            for day in o['Time Days/Date'][0]:
                course_data[6] = day
                output.append(course_data[:])


    csv_writer = csv.writer(open('courseb.csv', 'w'))
    for out in output:
        csv_writer.writerow(out)

if __name__ == '__main__':
    main()
